package com.seeyon.apps.exportExcelCtrl.manager.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.exportExcelCtrl.dao.ExportExcelCtrlDao;
import com.seeyon.apps.exportExcelCtrl.manager.ExportExcelCtrlManager;
import com.seeyon.apps.exportExcelCtrl.units.ExcelUtils;
import com.seeyon.apps.exportExcelCtrl.units.ExportExcelCtrlUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.Strings;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Title ExportExcelCtrlManagerImpl
 * @description: 领导数据导出自定义按钮manager实现类
 * @author wxt.daicheng
 * @date 2024/8/20 
 * @version 1.0
 */
public class ExportExcelCtrlManagerImpl implements ExportExcelCtrlManager {
    private ExportExcelCtrlDao exportExcelCtrlDao;
    private FormApi4Cap4 formApi4Cap4;
    private OrgManager orgManager;
    private EnumManager enumManagerNew;

    public void setEnumManagerNew(EnumManager enumManagerNew) {
        this.enumManagerNew = enumManagerNew;
    }

    public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
        this.formApi4Cap4 = formApi4Cap4;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public void setExportExcelCtrlDao(ExportExcelCtrlDao exportExcelCtrlDao) {
        this.exportExcelCtrlDao = exportExcelCtrlDao;
    }

    @Override
    public FlipInfo getLeaderList(FlipInfo fi, Map<String, Object> params) throws BusinessException {

        FormBean formBean = formApi4Cap4.getFormByFormCode(ExportExcelCtrlUtil.QX_FORM_CODE);
        List<JSONObject> list = new ArrayList<>();
        try {
            if (formBean != null){
                User currentUser = AppContext.getCurrentUser();
                String tableName = formBean.getMasterTableBean().getTableName();
                params.put("tableName",tableName);
                List<Map<String, Object>> leaderList = exportExcelCtrlDao.getLeaderList(params);
                if (leaderList != null && leaderList.size() > 0){
                    Map<String, Object> objectMap = leaderList.get(0);
                    Object id = objectMap.get("id");

                    FormDataMasterBean dataMasterBean = formApi4Cap4.getDataMasterBeanById(Long.valueOf(String.valueOf(id)), formBean, null);
                    if (dataMasterBean != null){
                        FormFieldBean ldFiled = formBean.getFieldBeanByDisplay("分管领导");
                        FormFieldBean llyFiled = formBean.getFieldBeanByDisplay("联络员");

                        FormTableBean subTableBean = formBean.getSubTableBean().get(0);
                        List<FormDataSubBean> subBeans = dataMasterBean.getSubTables().get(subTableBean.getTableName());

                        for (FormDataSubBean subBean : subBeans) {
                            //如果联络员中包含当前登录人id
                            String llyValue = String.valueOf(subBean.getFieldValue(llyFiled.getName()));
                            if (llyValue.contains(currentUser.getId().toString())){
                                //配置的领导数据
                                String ldValue = String.valueOf(subBean.getFieldValue(ldFiled.getName()));
                                JSONObject data = new JSONObject();
                                data.put("id",ldValue);
                                V3xOrgMember member = orgManager.getMemberById(Long.valueOf(ldValue));
                                data.put("name",member.getName());
                                list.add(data);
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            ExportExcelCtrlUtil.log("查询领导权限出错", "领导数据导出", e);
        }
        fi.setData(list);
        Strings.isNotBlank("");
        return fi;
    }

    @Override
    public File exportExcel(Map<String, Object> params) throws BusinessException, IOException {

        FormBean formBean = formApi4Cap4.getFormByFormCode(ExportExcelCtrlUtil.FORM_CODE);
        User currentUser = AppContext.getCurrentUser();
        if (formBean != null){
            String tableName = formBean.getMasterTableBean().getTableName();
            String field = formBean.getFieldBeanByDisplay("分管领导").getName();

            String leader = String.valueOf(params.get("leader"));

            if (Strings.isNotBlank(leader) && !"null".equals(leader)){
                String[] split = leader.split(",");
                //String[] 转list
                List<String> leaderList = new ArrayList<>();
                for (String s : split) {
                    leaderList.add(s);
                }
                //查询本次所选领导的所有数据
                List<Map<String, Object>> excelList = exportExcelCtrlDao.getExportExcelList(tableName, field, leaderList);

                String sxlb = formBean.getFieldBeanByDisplay("事项类别").getName();
                String date = DateUtil.format(new Date(), "yyyy年MM月dd日");
                Map<String, JSONObject> allData = new HashMap<>();

                for (Map<String, Object> objectMap : excelList) {

                    Object fgldObj = objectMap.get(field);
                    if (fgldObj == null){
                        continue;
                    }
                    String[] fgldIds = String.valueOf(fgldObj).split(",");
                    for (String fgldId : fgldIds){
                        JSONObject leaderData = allData.get(fgldId);
                        V3xOrgMember member = orgManager.getMemberById(Long.valueOf(fgldId));

                        if (leaderData == null){
                            leaderData = new JSONObject();
                            leaderData.put("leader",member.getName());
                            leaderData.put("date",date);
                            leaderData.put("createUser",currentUser.getName());
                            leaderData.put("id",fgldId);
                            allData.put(fgldId,leaderData);
                        }

                        Object sxlbObj = objectMap.get(sxlb);
                        if (sxlbObj == null){
                            continue;
                        }
                        CtpEnumItem cacheEnumItem = enumManagerNew.getCacheEnumItem(Long.valueOf(String.valueOf(sxlbObj)));
                        String label = cacheEnumItem.getLabel();

                        JSONObject sheetJs = null;
                        if (label.contains("市领导")){
                            JSONObject sldJs = leaderData.getJSONObject("市领导");
                            if (sldJs == null){
                                sldJs = new JSONObject();
                                sldJs.put("date",date);
                                sldJs.put("createUser",currentUser.getName());
                                sldJs.put("leader",member.getName());
                            }
                            leaderData.put("市领导",sldJs);
                            sheetJs = sldJs;
                        }else if (label.contains("总经理")){
                            JSONObject zjlJs = leaderData.getJSONObject("总经理");
                            if (zjlJs == null){
                                zjlJs = new JSONObject();
                                zjlJs.put("date",date);
                                zjlJs.put("createUser",currentUser.getName());
                                zjlJs.put("leader",member.getName());
                            }
                            leaderData.put("总经理",zjlJs);
                            sheetJs = zjlJs;
                        }else if (label.contains("党委主要领导")){
                            JSONObject dwJs = leaderData.getJSONObject("党委主要领导");
                            if (dwJs == null){
                                dwJs = new JSONObject();
                                dwJs.put("date",date);
                                dwJs.put("createUser",currentUser.getName());
                                dwJs.put("leader",member.getName());
                            }
                            leaderData.put("党委主要领导",dwJs);
                            sheetJs = dwJs;
                        }
                        //过滤掉没有对应事项类别的数据
                        if (sheetJs == null){
                            continue;
                        }

                        String sxzt = formBean.getFieldBeanByDisplay("事项状态").getName();
                        Object sxztObj = objectMap.get(sxzt);
                        //过滤事项状态为空的数据
                        if (sxztObj == null){
                            continue;
                        }
                        //判断数据的事项状态
                        CtpEnumItem sxztItem = enumManagerNew.getCacheEnumItem(Long.valueOf(String.valueOf(sxztObj)));
                        String sxztItemLabel = sxztItem.getLabel();
                        JSONArray ztList = null;
                        boolean isEnd = false;
                        if (sxztItemLabel.contains("欠序时")){
                            JSONArray todo = sheetJs.getJSONArray("todo");
                            if (todo == null){
                                todo = new JSONArray();
                            }
                            sheetJs.put("todo",todo);
                            ztList = todo;
                        }else if (sxztItemLabel.contains("推进中")){
                            JSONArray promote = sheetJs.getJSONArray("promote");
                            if (promote == null){
                                promote = new JSONArray();
                            }
                            sheetJs.put("promote",promote);
                            ztList = promote;
                        }else if (sxztItemLabel.contains("已完成")){
                            JSONArray end = sheetJs.getJSONArray("end");
                            if (end == null){
                                end = new JSONArray();
                            }
                            sheetJs.put("end",end);
                            ztList = end;
                            isEnd = true;
                        }
                        if (ztList != null){
                            int size = ztList.size();
                            JSONArray data = new JSONArray();
                            ztList.add(data);
                            data.add(size + 1); //序号
                            String jblx = formBean.getFieldBeanByDisplay("交办类型").getName();
                            Object jblxObj = objectMap.get(jblx);
                            if (jblxObj != null){
                                CtpEnumItem jblxItem = enumManagerNew.getCacheEnumItem(Long.valueOf(String.valueOf(jblxObj)));
                                data.add(jblxItem.getLabel());//交办类型
                            }else {
                                data.add(""); //交办类型
                            }

                            String sxmc = formBean.getFieldBeanByDisplay("相关事项").getName();
                            data.add(objectMap.get(sxmc));//相关事项
                            String jbrq = formBean.getFieldBeanByDisplay("交办日期").getName();
                            Object jbrqObj = objectMap.get(jbrq);
                            if (jbrqObj != null){
                                data.add(DateUtil.format((Date) jbrqObj, "yyyy-MM-dd"));//交办日期
                            }else {
                                data.add("");//交办日期
                            }
                            String jbnr = formBean.getFieldBeanByDisplay("交办内容").getName();
                            Object jbnrObj = objectMap.get(jbnr);
                            jbnrObj = jbnrObj == null ? "" : jbnrObj;
                            data.add(jbnrObj);//交办内容
                            String lsqk = formBean.getFieldBeanByDisplay("落实情况").getName();
                            Object lsqkObj = objectMap.get(lsqk);
                            lsqkObj = lsqkObj == null ? "" : lsqkObj;
                            data.add(lsqkObj);//落实情况
                            data.add(isEnd?"是":"否");//是否完成

                            String zrbm = formBean.getFieldBeanByDisplay("责任部门").getName();
                            Object zrbmObj = objectMap.get(zrbm);
                            if (zrbmObj != null){
                                String zrbmStr = String.valueOf(zrbmObj);
                                String[] zrbmIds = zrbmStr.split(",");
                                String zrbmStrLabel = "";
                                for (String zrbmId : zrbmIds) {
                                    V3xOrgDepartment department = orgManager.getDepartmentById(Long.valueOf(zrbmId));
                                    zrbmStrLabel += department.getName() + ",";
                                }
                                zrbmStrLabel = zrbmStrLabel.substring(0,zrbmStrLabel.length() - 1);
                                data.add(zrbmStrLabel);//责任部门
                            }else {
                                data.add("");//责任部门
                            }
                            //责任人
                            String zrry = formBean.getFieldBeanByDisplay("责任人员").getName();
                            Object zrryObj = objectMap.get(zrry);
                            if (zrryObj != null){
                                String zrryStr = String.valueOf(zrryObj);
                                String[] zrbmIds = zrryStr.split(",");
                                String zrbmStrLabel = "";
                                for (String zrbmId : zrbmIds) {
                                    V3xOrgMember department = orgManager.getMemberById(Long.valueOf(zrbmId));
                                    zrbmStrLabel += department.getName() + ",";
                                }
                                zrbmStrLabel = zrbmStrLabel.substring(0,zrbmStrLabel.length() - 1);
                                data.add(zrbmStrLabel);//责任人员
                            }else {
                                data.add("");//责任人员
                            }
                            //分管领导
                            if (fgldObj != null){
                                String fgldStr = String.valueOf(fgldObj);
                                String[] zrbmIds = fgldStr.split(",");
                                String fgldStrLabel = "";
                                for (String zrbmId : zrbmIds) {
                                    V3xOrgMember department = orgManager.getMemberById(Long.valueOf(zrbmId));
                                    fgldStrLabel += department.getName() + ",";
                                }
                                fgldStrLabel = fgldStrLabel.substring(0,fgldStrLabel.length() - 1);
                                data.add(fgldStrLabel);//责任领导
                            }else {
                                data.add("");//责任领导
                            }
                            String wcqx = formBean.getFieldBeanByDisplay("完成期限").getName();
                            Object wcqxObj = objectMap.get(wcqx);
                            if (wcqxObj != null){
                                data.add(DateUtil.format((Date) wcqxObj, "yyyy-MM-dd HH:mm:ss"));//完成期限
                            }else {
                                data.add("");//完成期限
                            }
                            //备注
                            String bz = formBean.getFieldBeanByDisplay("备注").getName();
                            Object bzObj = objectMap.get(bz);
                            bzObj = bzObj == null ? "" : bzObj;
                            data.add(bzObj);//交办内容
                        }
                    }
                }
                //封装excel文件
                List<File> allFile = new ArrayList<>();
                for (String key : allData.keySet()) {
                    if (leader.contains(key)){
                        File export = ExcelUtils.export(allData.get(key));
                        allFile.add(export);
                    }
                }
                //文件导出
                if (allFile.size() == 1){
                    return allFile.get(0);
                }else if (allFile.size() > 1){
                    String path = SystemEnvironment.getSystemTempFolder() + File.separator  + DateUtil.format(new Date(), "yyyy-MM-dd-HHmmss") + ".zip";
                    //多个文件打包下载
                    File zipFile = new File(path);
                    if (zipFile.exists()) {
                        zipFile.delete();
                    }
                    ExcelUtils.compressFiles(allFile, zipFile);
                    return zipFile;
                }

            }
        }
        return null;
    }
}
